<?php

include_once 'DataProvider.php';
include_once 'Entity.php';
include_once 'SimpleImage.php';

class Sanpham extends Entity {

    public $dataProvider;

    const IMG_PATH = "/quocha/upload/sanpham"; // Duong dan tuong doi den thu muc chua anh

    public function __construct() {
        $this->dataProvider = new DataProvider();
    }

    public function layDanhSachSanPham() {
        $sql = "select sanpham.*,danhmuc.* from `sanpham` LEFT JOIN danhmuc ON sanpham.danhmuc_id = danhmuc.id";
        $tmp = $this->dataProvider->ExecuteQuery($sql);
        $result = array();
        while ($row = mysql_fetch_assoc($tmp)) {
            $result[] = $row;
        }
        return $result;
    }
    
    public function layDSSanPham($danhmuc_id) {
        $sql = "select * from `sanpham` where trangthai='" . self::HIEN . "' and danhmuc_id='" . $danhmuc_id . "' order by ngaycapnhat desc limit 2";
        $tmp = $this->dataProvider->ExecuteQuery($sql);
        $result = array();
        while ($row = mysql_fetch_assoc($tmp)) {
            $result[] = $row;
        }
        return $result;
    }
    
    public function layDSSP() {
        $sql = "select sanpham.*,danhmuc.tieude from `sanpham` LEFT JOIN danhmuc ON sanpham.danhmuc_id = danhmuc.id";
        $tmp = $this->dataProvider->ExecuteQuery($sql);
        $result = array();
        while ($row = mysql_fetch_assoc($tmp)) {
            $result[] = $row;
        }
        return $result;
    }

    /**
     * @param String $idsStr co dang 1,2,3,5
     * @return resource tr
     */
    public function laySanPhamGioHang() {

        $giohang = $this->layGioHang();
        $nLent = count($giohang);
        if ($nLent > 0) {   // Truong hop gio hang da co san pham     
            $sql = "select * from sanpham where sanpham.id in ({$this->xuLyChuoiGioHang($giohang)})";
            $query = DataProvider::ExecuteQuery($sql);
            $ketQua = array();
            while ($row = mysql_fetch_array($query)) {
                $tmpArr = array();
                $tmpArr['id'] = $row['id'];
                $tmpArr['ten'] = $row['ten'];
                $tmpArr['gia'] = $row['gia'];
                $tmpArr['soluong'] = $giohang[$row['id']];
                $tmpArr['thanhtien'] = $row['gia'] * $tmpArr['soluong'];
                $ketQua[] = $tmpArr;
            }
            return $ketQua;
        } else { // Truong hop gio hang khong co san pham
            return array();
        }
    }

    private function xuLyChuoiGioHang($bien_giohang) {
        foreach ($bien_giohang as $k => $v) {
            if (trim($k) == "")
                unset($bien_giohang[$k]);
        }
        $i = 0;
        $tmpStr = "";
        $nLent = count($bien_giohang);

        foreach ($bien_giohang as $k => $v) {
            $tmpStr = $tmpStr . $k;
            if ($i++ < $nLent - 1)
                $tmpStr = $tmpStr . ",";
        }
        return $tmpStr;
    }

    private function layGioHang() {
        if (isset($_SESSION['giohang']) && is_array($_SESSION['giohang'])) {
            return $_SESSION['giohang'];
        }
        return array(); // Neu chua co gio hang thi tra ve array rong
    }

    public function demSanPham() {
        $sql = "select count(id) from `sanpham`";
        return DataProvider::GetOneRowi($sql);
    }

    public function xoaSanPham($id) {
        $sql = "DELETE FROM `sanpham` WHERE id = '" . $id . "'";
        return DataProvider::ExecuteQuery($sql);
    }

    public function laySanPham($id) {
        $sql = "SELECT * from `sanpham` WHERE `sanpham`.id = '$id'";
        return DataProvider::GetOneRow($sql);
    }

    public function laySanPhamMoiNhat() {
        $sql = "SELECT * FROM sanpham where trangthai='" . self::HIEN . "' order by ngaycapnhat desc limit 12";
        $result = $this->dataProvider->ExecuteQuery($sql);
        return $result;
    }

    public function laySanPhamTheoDanhMuc($danhmuc_id) {
        $sql = "SELECT * FROM sanpham where trangthai='" . self::HIEN . "' and danhmuc_id='" . $danhmuc_id . "' order by ngaycapnhat desc limit 9";
        $result = $this->dataProvider->ExecuteQuery($sql);
        return $result;
    }
    
    public function layDanhMuc() {
        $sql = "select * from danhmuc";
        $result = $this->dataProvider->ExecuteQuery($sql);
        return $result;
    }

    public function demSanPhamTheoDanhMuc($danhmuc_id) {
        $sql = "SELECT * FROM sanpham where trangthai='" . self::HIEN . "' and danhmuc_id='" . $danhmuc_id . "' order by ngaycapnhat desc limit 9";
        $result = $this->dataProvider->ExecuteQuery($sql);
        return mysql_num_rows($result);
    }

    public function laySanPhamDacBiet() {
        $sql = "SELECT * FROM sanpham where trangthai='" . self::HIEN . "' and dacbiet='" . self::DUNG . "' order by ngaycapnhat desc limit 2";
        $result = $this->dataProvider->ExecuteQuery($sql);
        return $result;
    }

    public function capnhapSanPham($id, $data) {
        $this->locdulieuCapnhat($data);

        $sql = "UPDATE `sanpham` 
                SET `sanpham`.ten = '{$data['ten']}', 
                    `sanpham`.danhmuc_id= '{$data['danhmuc_id']}',
                    `sanpham`.gia= '{$data['gia']}',
                    `sanpham`.mota= '{$data['mota']}',
                    `sanpham`.size= '{$data['size']}',
                    `sanpham`.mau= '{$data['mau']}',
                    `sanpham`.chatlieu= '{$data['chatlieu']}',
                    `sanpham`.dacbiet= '{$data['dacbiet']}',
                    `sanpham`.trangthai= '{$data['trangthai']}',
                    `sanpham`.ngaycapnhat= '" . date("Y-m-d H:i:s", time()) . "'
                where `sanpham`.id = '$id'";
        $result = $this->dataProvider->ExecuteQuery($sql);
        return $result;
    }

    public function themmoiSanPham($data) {
        $this->locdulieuCapnhat($data);
        $sql = "insert into `sanpham` (ten,danhmuc_id,gia,mota,dacbiet,size,chatlieu,mau,trangthai,ngaycapnhat) values ('$data[ten]','$data[danhmuc_id]','$data[gia]','$data[mota]','$data[dacbiet]','$data[size]','$data[chatlieu]','$data[mau]','$data[trangthai]','" . date("Y-m-d H:i:s", time()) . "')";
        return DataProvider::ExecuteQuery($sql);
    }

    public function uploadFile($imgUpload, $productId, $command = 'new', $isDel = false) {
        $imageUntil = new SimpleImage();

        if ($command == 'new') { // Truong hop them moi san pham
            if ((($imgUpload["type"] == "image/gif")
                    || ($imgUpload["type"] == "image/jpeg")
                    || ($imgUpload["type"] == "image/png")
                    || ($imgUpload["type"] == "image/pjpeg"))
            ) { // Xay ra khi co up hinh
//----------------------------------------
                if ($imgUpload["error"] <= 0) {
                    $destination = self::IMG_PATH . "/" . time() . $imgUpload["name"];
                    $imageUntil->load($imgUpload["tmp_name"]); //Load hinh 
                    $imageUntil->resizeToWidth(300); // Nen hinh
                    $imageUntil->save($_SERVER['DOCUMENT_ROOT'] . $destination); // Chuyen vao thu muc upload/sanpham
                    $sql = "UPDATE `sanpham` 
                            SET `sanpham`.hinhanh= '$destination'
                            where `sanpham`.id = '$productId'";
                    $this->dataProvider->ExecuteQuery($sql);
                }
//------------------------------------------
            }
        } else {
            if ((($imgUpload["type"] == "image/gif")
                    || ($imgUpload["type"] == "image/jpeg")
                    || ($imgUpload["type"] == "image/png")
                    || ($imgUpload["type"] == "image/pjpeg"))
            ) {
//----------------------------------------
                if ($imgUpload["error"] <= 0) {
//Xoa hinh cu
                    $hinhCu = $this->layHinh($productId);
                    if (file_exists($_SERVER['DOCUMENT_ROOT'] . $hinhCu)) {
                        unlink($_SERVER['DOCUMENT_ROOT'] . $hinhCu);
                    }
//Cap nhat hinh moi
                    $destination = self::IMG_PATH . "/" . time() . $imgUpload["name"];
                    $imageUntil->load($imgUpload["tmp_name"]); //Load hinh 
                    $imageUntil->resizeToWidth(300); // Nen hinh
                    $imageUntil->save($_SERVER['DOCUMENT_ROOT'] . $destination); // Chuyen vao thu muc upload/sanpham
                    $sql = "UPDATE `sanpham` 
                            SET `sanpham`.hinhanh= '$destination'
                            where `sanpham`.id = '$productId'";
                    $this->dataProvider->ExecuteQuery($sql);
                }
//------------------------------------------
            } else { //Trong truong hop sua khong up hinh moi
                if ($isDel) { // Muon xoa hinh cu
                    $hinhCu = $this->layHinh($productId);
                    if (file_exists($_SERVER['DOCUMENT_ROOT'] . $hinhCu)) {
                        unlink($_SERVER['DOCUMENT_ROOT'] . $hinhCu);
                        $sql = "UPDATE `sanpham` 
                                SET `sanpham`.hinhanh= ''
                                where `sanpham`.id = '$productId'";
                        $this->dataProvider->ExecuteQuery($sql);
                    }
                }
            }
        }
    }

    public function layHinh($id) {
        $sql = "select sanpham.hinhanh from sanpham WHERE sanpham.id=$id";
        $result = $this->dataProvider->GetOneRow($sql);
        return $result['hinhanh'];
    }

    public $data = array();
//     public $tuoi = 100;
    public function __get($key){
         return $this->data[$key];
    }
    
    public function __set($key,$value){
        $this->data[$key] = $value;
    }
}
?>
